﻿#region
using System.Windows.Forms;
using Y2M.Components;
using System.Linq;
#endregion

namespace Y2M.Controls
{
    public partial class DownloadManagerControl : UserControl
    {
        public DownloadManagerControl()
        {
            InitializeComponent();
        }

        public void Add(ClipInfo clipInfo, bool audioOnly, string origianlUrl)
        {
            DownloadingList.Instance.Add(origianlUrl);


            SuspendLayout();

            DownloadControl control = new DownloadControl();
            control.Height = 45;
            control.Margin = new Padding(5);
            control.Dock = DockStyle.Top;
            pnlContainer.Controls.Add(control);
            control.BringToFront();
            control.CloseButtonClicked += Control_CloseButtonClicked;
            control.OriginalUrl = origianlUrl;

            control.AddItem(new DownloadInfo(clipInfo, audioOnly));

            ResumeLayout();
        }

        private void Control_CloseButtonClicked(object sender, DownloadControl.CloseButtonClickedEventArgs e)
        {
            SuspendLayout();

            pnlContainer.Controls.Remove((Control) sender);

            ResumeLayout();
        }

        private void btnRemoveCompleted_Click(object sender, System.EventArgs e)
        {
            SuspendLayout();

            // foreach로 열거 중에 아이템을 삭제하면 안됨.
            for (int i = pnlContainer.Controls.Count - 1; i >= 0; i--)
                if (((DownloadControl)pnlContainer.Controls[i]).DownloadCompledted)
                    pnlContainer.Controls.RemoveAt(i);

            ResumeLayout();
        }
    }
}